/**
 * 市场可视化工具类
 * 用于输出市场状态和投资者持仓等信息
 */
class MarketVisualizer {
  /**
   * 显示市场概览
   * @param {MarketEnvironment} market - 市场环境
   */
  static displayMarketOverview(market) {
    console.log('\n========== 市场概览 ==========');
    console.log(`时间: ${market.time}`);
    
    console.log('\n--- 资产价格 ---');
    for (const [id, asset] of market.assets) {
      console.log(`${asset.name} (${id}): ¥${asset.getPrice().toFixed(2)}`);
    }
    
    console.log('\n--- 投资者统计 ---');
    const investorStats = {};
    for (const [_, investor] of market.investors) {
      const type = investor.getType();
      if (!investorStats[type]) {
        investorStats[type] = { count: 0, totalValue: 0 };
      }
      investorStats[type].count++;
      investorStats[type].totalValue += investor.getTotalValue(market.getAllAssetPrices());
    }
    
    for (const [type, stats] of Object.entries(investorStats)) {
      console.log(`${type}: ${stats.count} 人, 总资产: ¥${stats.totalValue.toFixed(2)}`);
    }
  }

  /**
   * 显示特定投资者的持仓情况
   * @param {Investor} investor - 投资者
   * @param {Map} marketPrices - 市场价格
   */
  static displayInvestorPositions(investor, marketPrices) {
    console.log(`\n---------- ${investor.name} (${investor.getType()}) ----------`);
    console.log(`现金: ¥${investor.capital.toFixed(2)}`);
    
    if (investor.positions.size > 0) {
      console.log('持仓:');
      for (const [assetId, position] of investor.positions) {
        const marketPrice = marketPrices.get(assetId) || 0;
        const currentValue = position.quantity * marketPrice;
        const costBasis = position.quantity * position.avgPrice;
        const pnl = currentValue - costBasis;
        
        console.log(`  ${assetId}: ${position.quantity} 股 @ 平均价 ¥${position.avgPrice.toFixed(2)}`);
        console.log(`    当前价值: ¥${currentValue.toFixed(2)}, 收益: ¥${pnl.toFixed(2)}`);
      }
    } else {
      console.log('无持仓');
    }
    
    console.log(`总资产: ¥${investor.getTotalValue(marketPrices).toFixed(2)}`);
  }

  /**
   * 显示订单簿
   * @param {OrderBook} orderBook - 订单簿
   */
  static displayOrderBook(orderBook) {
    console.log(`\n---------- 订单簿 (${orderBook.assetId}) ----------`);
    
    console.log('买单:');
    if (orderBook.buyOrders.length > 0) {
      for (let i = 0; i < Math.min(5, orderBook.buyOrders.length); i++) {
        const order = orderBook.buyOrders[i];
        console.log(`  价格: ¥${order.price.toFixed(2)}, 数量: ${order.quantity}, 投资者: ${order.investorId.substring(0, 8)}`);
      }
    } else {
      console.log('  无买单');
    }
    
    console.log('卖单:');
    if (orderBook.sellOrders.length > 0) {
      for (let i = 0; i < Math.min(5, orderBook.sellOrders.length); i++) {
        const order = orderBook.sellOrders[i];
        console.log(`  价格: ¥${order.price.toFixed(2)}, 数量: ${order.quantity}, 投资者: ${order.investorId.substring(0, 8)}`);
      }
    } else {
      console.log('  无卖单');
    }
  }
}

module.exports = MarketVisualizer;